//
//  TRSearchTagsEditView.m
//  WeiMiLan
//
//  Created by anan on 14/12/11.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRSearchTagsEditView.h"
#import "TRUserhomeViewController.h"

@interface TRSearchTagsEditView ()
@property (nonatomic,assign) int nextPage;
@property (nonatomic,assign) int currentPage;
@end

@implementation TRSearchTagsEditView

- (NSMutableArray *)usersList {
    if (_usersList == nil) {
        _usersList = [NSMutableArray array];
    }
    return _usersList;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.currentPage = 1;
}

- (void)reload
{
    
    [self initSeachButton];
    
    [self seachRequest];
    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self addGestureRecognizer:tapGr];
    // [self.textFieldContent resignFirstResponder];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchButtonClicked:) name:@"searchBarSearchButtonClickedOther" object:nil];
}

-(void)initSeachButton
{
    
}

- (void)searchButtonClicked: (NSNotification *)noti {
    NSLog(@"%@",noti);
    //NSLog(@"－－－－－接收到通知------");
    
    NSDictionary *dict = noti.userInfo;
    NSString *searchText = dict[@"text"];
    [self buttonSearchAction:searchText];
}

-(void)seachRequest{
    [ApplicationDelegate.webAPI getWebAPIWithParams:@{TYPE:@"1024"} andMethodNode:NODE_DIRECTORY completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        if (state ==1) {
            
            if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
                NSArray * arr = responseObject[@"PACKAGE_RSP"][@"PACKAGE"];
                _titlesArray = [@[]mutableCopy];
                
                for (NSDictionary * nameArr in arr) {
                    [_titlesArray addObject:nameArr[@"NAME"]];
                }
            //    self.isShowArr = _titlesArray;
                [self seachHotWord:_titlesArray];
            }
            
        }
    }];
}

-(void)seachHotWord:(NSArray *)titlesArrs
{
    
    
    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[UILabel class]]) {
            [subView removeFromSuperview];
        }
    }
    
//    [self.isShowArr removeAllObjects];
    
//    self.isShowArr = [NSMutableArray arrayWithArray:titlesArrs];
    
    NSMutableArray *colorArray = [@[[UIColor greenColor],[UIColor blueColor],[UIColor purpleColor],[UIColor redColor],[UIColor grayColor],[UIColor magentaColor],[UIColor brownColor],[UIColor yellowColor],[UIColor cyanColor]]mutableCopy];
    NSMutableArray *frameArray = [[NSMutableArray alloc] initWithObjects:@"{{54, 111}, {200, 70}}",@"{{26, 228}, {120, 70}}",@"{{132, 124}, {50, 70}}",@"{{64, 146}, {120, 80}}",@"{{180, 175}, {420, 70}}",@"{{54, 190}, {120, 40}}",@"{{132, 238}, {44, 70}}",@"{{170, 269}, {200, 70}}",@"{{47, 290}, {10, 70}}", nil];
    //如果文字给颜色多，颜色就自我复制
    while (titlesArrs.count>colorArray.count) {
        [colorArray addObjectsFromArray:colorArray];
    }
    NSMutableArray * labelArr = [@[]mutableCopy];
    
    
    for (int i = 0 ;i<titlesArrs.count;i++) {
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectZero];
        
        label.text = [titlesArrs objectAtIndex:i];
        int num = arc4random()%[colorArray count];
        label.textColor = colorArray[num];
        [colorArray removeObjectAtIndex:num];
        label.font = [UIFont boldSystemFontOfSize:k_FontSize];
        [self addSubview:label];
        
        label.center = self.center;
        [labelArr addObject:label];
        label.userInteractionEnabled = YES;
        //加手势
        UITapGestureRecognizer * tapVc = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didselectText:)];
        [label addGestureRecognizer:tapVc];
    }
    
    
    NSString * frameString;
    while (titlesArrs.count>=frameArray.count) {
        
        
        int w = arc4random()%100+44;
        int h = arc4random()%100+100;
        int x=arc4random()%(int)(320-w/2)+w/2;
        int y= arc4random()%(int)(568-h/2-44)+100;
        frameString = [NSString stringWithFormat:@"{{%d, %d}, {%d, %d}}",x,y,w,h];
        
        //   NSLog(@"%@",frameString);
        if (![frameArray containsObject:frameString]) {
            [frameArray addObject:frameString];
        }
        
        
        
    }
    
    for (int i = 0 ;i<labelArr.count;i++) {
        
        UIView *label = labelArr[i];
        
        if ([label isMemberOfClass:[UILabel class]]) {
            int rand =arc4random()%[frameArray count];
            [UIView animateWithDuration:2 animations:^{
                
                label.frame = CGRectFromString(frameArray[rand]);
                NSLog(@"%@",frameArray[rand]);
                
            } completion:nil];
            [label sizeToFit];
            [frameArray removeObjectAtIndex:rand];
            
        }
        
    }
    if (titlesArrs.count > 0) {
        titlesArrs = nil;
    }
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr{
    [self.textFieldContent resignFirstResponder];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"viewTapped" object:nil userInfo:nil];
}

- (void)buttonSearchAction:(NSString *)sender
{
    if (sender.length==0) {
        [SVProgressHUD showErrorWithStatus:@"请输入私募"];
        return;
    }
    
    [self loadUserIDs:sender];
    


}

- (void)loadUserIDs:(NSString *)sender{

     [self showLoadingViewWithText:@"搜索中..."];
    
    NSString *url = [NSString stringWithFormat:@"http://ping.vsmu.cn/app/Interface/Package?type=1010&PAGE_NUM=%zd&BID=%@&userId=%@",self.currentPage,sender,ApplicationDelegate.currentUserId];
//    NSLog(@"===%@",url);
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
            //第一页
            NSArray *arr =  responseObject[@"PACKAGE_RSP"][@"PACKAGE"];
            
            
            for (NSDictionary *dicts in arr) {
                NSString *userID = dicts[@"USER_ID"];
                if (![self.usersList containsObject:userID]) {
                    [self.usersList addObject:userID];
                }
            }
            NSDictionary *pageInfo = responseObject[@"PAGE_INFO"];
            self.nextPage = [pageInfo ql_intForKey:@"PAGES"];
            self.currentPage = [pageInfo ql_intForKey:@"NUMBER"] + 1;
            if (self.nextPage>self.currentPage) {
                //     refreshFooterView.isend = NO;
                
                [self loadUserIDs:sender];
                
            } else {
                [self dismissLoadingView];
                [SVProgressHUD showSuccessWithStatus:@"查询成功"];
          //      NSLog(@"---%@",self.usersList);
                [self seachHotWord:self.usersList];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self dismissLoadingView];
        [SVProgressHUD showErrorWithStatus:@"暂无此用户"];
    }];

}

- (NSMutableDictionary * )goodsListDictByArray:(NSArray *)array
{
    NSMutableDictionary *dict=[@{}mutableCopy];
    for (NSDictionary *d in array) {
        [dict setObject:d[@"ID"] forKey:d[@"NAME"]];
    }
    return dict;
}

- (IBAction)buttonAllAction:(id)sender
{
    self.textFieldContent.text=@"";
    ApplicationDelegate.markString=@"";
    ApplicationDelegate.markDictionary=nil;
    [SVProgressHUD showSuccessWithStatus:@"显示全部"];
    //[ApplicationDelegate.rootVC.mydelegate menuViewDidSelecte:-1];
    //root刷新
    
    [QLPropertyUtils putStringByKey:@"BID" value:@""];
    
    //切换到分类tab
    TRTabBarViewController *tabVc =ApplicationDelegate.rootVC;
    [tabVc.customTabBarView changAction:tabVc.customTabBarView.button2];;
    for (UINavigationController *nv in tabVc.viewControllers) {
        UIViewController *vc = [nv.viewControllers firstObject];
      //  NSLog(@"%@",[vc class]);
        if ([vc isMemberOfClass:[TRTypeViewController class]]) {
            TRTypeViewController * menuVc =(TRTypeViewController *)vc;
            if ([menuVc respondsToSelector:@selector(searchData:)]) {
                [menuVc performSelector:@selector(searchData:) withObject:nil afterDelay:0.5];
            }
        }
    }
    
    ApplicationDelegate.markIsChang=YES;
    [ApplicationDelegate.ddVC showRootController:YES];
    [self.viewController.navigationController popViewControllerAnimated:YES];
}

- (void)didselectText:(UITapGestureRecognizer*)tap{
    UILabel * label = (UILabel *)tap.view;
    
    
    if(self.usersList.count > 0) {
        
        [QLPlayerManager openUserHomeWithId:[label.text intValue] viewController:self.viewController                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         ];
    } else {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"didselectText" object:nil userInfo:@{@"text": label.text, @"label": label}];
    }

    
  //   [[NSNotificationCenter defaultCenter] postNotificationName:@"didselectText" object:nil userInfo:@{@"text": label.text, @"label": label}];
//    TRUserhomeViewController *home = [[TRUserhomeViewController alloc]init];
//    home.userId = [label.text intValue];
//    [home loadData:1];
//    home.hidesBottomBarWhenPushed = YES;
//    [self.viewController.navigationController pushViewController:home animated:YES];
    
    
}

@end
